<?php

namespace app\api\controller;

use addons\jiezicommon\service\Tools;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'logout', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'apply_find_pwd', 'common', 'clac_order_total', 'auto_set_calc_type', 'auto_transfer_point'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }



    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="昵称、id号", default="13011112222")
     * @ApiParams (name="password", type="string", required=true, description="密码", default="111111")
     * @ApiParams (name="mini_code", type="string", required=false, description="小程序code", default="")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $mini_code = $this->request->param('mini_code');
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $user_id = $this->auth->id;
            if($mini_code){
                $config = Tools::getInstance()->getMiniProgram();
                try {
                    $app = Factory::miniProgram($config);
                    $result = $app->auth->session($mini_code);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
                if (empty($result['errcode'])) {
                    $openid = $result['openid'];
                    $platform = 'wechat_mini';
                    $third = \addons\third\model\Third::get(['platform' => $platform, 'openid' => $openid]);
                    $third2 = \addons\third\model\Third::get(['platform' => $platform, 'user_id' => $user_id]);
                    if($third2){
                        if($third && $third['user_id'] != $user_id){
                            $third->delete();
                        }
                        if($third2['openid'] != $openid){
                            $third2->openid = $openid;
                            $third2->save();
                        }
                    }else{
                        if(!$third){
                            \addons\third\model\Third::create([
                                'user_id' => $user_id,
                                'platform' => $platform,
                                'openid' => $openid,
                                'access_token' => '',
                                'createtime' => time(),
                                'updatetime' => time(),
                                'logintime' => time(),
                            ]);
                        }elseif($third['user_id']!= $user_id){
                            $third->user_id = $user_id;
                            $third->save();
                        }
                    }
                }
            }
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiInternal
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        return;
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="password2", type="string", required=true, description="密码2")
     * @ApiParams (name="pay_password", type="string", required=true, description="支付密码")
     * @ApiParams (name="pay_password2", type="string", required=true, description="支付密码2")
     * @ApiParams (name="spread_spid", type="string", required=false, description="邀请码")
     * @ApiParams (name="mini_code", type="string", required=true, description="小程序code")
     */
    public function register()
    {
        $nickname = $this->request->post('nickname');//账号
        $password = $this->request->post('password');
        $password2 = $this->request->post('password2');
        $pay_password = $this->request->post('pay_password');
        $pay_password2 = $this->request->post('pay_password2');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$nickname || !$password || !$pay_password) {
            $this->error(__('Invalid parameters'));
        }
        if($password != $password2){
            $this->error('两次密码不一致');
        }
        if($pay_password != $pay_password2){
            $this->error('两次支付密码不一致');
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if(Validate::regex($nickname, "^\d+$")){
            $this->error('昵称不能为纯数字');
        }
//        var_dump($nickname);die;
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $mini_code = $this->request->param('mini_code');

        $spread_spid = $this->request->post('spread_spid');
        if(!empty($spread_spid)){
//            $hashids_obj = new \Hashids\Hashids(config('hashid_key'));
//            try {
//                list($user_id) = $hashids_obj->decode($spread_spid);
//            }catch (\Exception $e){
//                $this->error('邀请码错误');
//                var_dump($e->getMessage());die;
//            }
//            $user_id = \app\common\model\InviteCode::where("code", $spread_spid)->value('user_id');
            $user_id = $spread_spid;
            $spread_uid = $user_id;
            $spread_user = \app\common\model\User::get($spread_uid);
            if($spread_user && $spread_user['status'] != 'hidden'){
                $spread_spid = $spread_user['id'];
            }else{
                $spread_spid = 0;
            }
        }else{
            $spread_spid = 0;
        }
        //邀请者
        $extend = [
//            'nickname' => $nickname,
            'parent_id' => $spread_spid,
            'group_id' => 1,
            'salt' => Random::alnum(),
            'id' => \addons\jiezicommon\service\Tools::gen_code(),
        ];
        // var_dump($extend);die;
        $extend['pay_password'] = $this->auth->getEncryptPassword($pay_password, $extend['salt']);
        $username = $nickname;
        $ret = $this->auth->register($username, $password, $email, $mobile, $extend);
        if ($ret) {
            $user_id = $this->auth->id;
            //更新invite_code表code被使用
            \app\common\model\InviteCode::where('code', $user_id)->update(['user_id' => $user_id]);
            if($mini_code){
                $config = Tools::getInstance()->getMiniProgram();
                try {
                    $app = Factory::miniProgram($config);
                    $result = $app->auth->session($mini_code);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
                if (empty($result['errcode'])) {
                    $openid = $result['openid'];
                    $platform = 'wechat_mini';
                    $third = \addons\third\model\Third::get(['platform' => $platform, 'openid' => $openid]);
                    $third2 = \addons\third\model\Third::get(['platform' => $platform, 'user_id' => $user_id]);
                    if($third2){
                        if($third['user_id'] != $user_id){
                            $third->delete();
                        }
                        if($third2['openid'] != $openid){
                            $third2->openid = $openid;
                            $third2->save();
                        }
                    }else{
                        if(!$third){
                            \addons\third\model\Third::create([
                                'user_id' => $user_id,
                                'platform' => $platform,
                                'openid' => $openid,
                                'access_token' => '',
                                'createtime' => time(),
                                'updatetime' => time(),
                                'logintime' => time(),
                            ]);
                        }elseif($third['user_id']!= $user_id){
                            $third->user_id = $user_id;
                            $third->save();
                        }
                    }
                }
            }
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 用户详细
     * @ApiMethod (POST)
     */
    public function detail(){
        $userinfo = $this->auth->getUserinfo();
        $userinfo['erweima'] = '';
//        $hashids_obj = new \Hashids\Hashids(config('hashid_key'));
//        $en_code = $hashids_obj->encode($userinfo['id'], config('hashid_key'));
//        $en_code = \addons\jiezicommon\service\Tools::gen_code($userinfo['id']);
        $en_code = $userinfo['id'];
        $userinfo['erweima_code'] = $en_code;
        $config = Tools::getInstance()->getMiniProgram();
        $app = \EasyWeChat\Factory::miniProgram($config);
        $scene = $arr['query'] ?? '';
        $page = $arr['path'] ?? '';
        $width = 200;
        $page = 'pages/login/reg';
        $scene = 'code=' . $en_code;
//            var_dump($scene);die;
        $response = $app->app_code->getUnlimit($scene, [
            'page' => $page,
            'check_path' => false,
            'width' => $width,
//                'env_version' => 'develop',
//                'env_version' => 'trial',
        ]);

        if (is_array($response)) {
            $this->error($response['errmsg']);
            die;
        }
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $response->getBody()->rewind();
//            $filename = $response->save('.' . $image, $filename);
            ob_start();
            // 输出图像
            $res = imagecreatefromstring($response->getBodyContents());
            imagepng($res);
            $content = ob_get_clean();
            imagedestroy($res);
            $userinfo['erweima'] = 'data:image/png;base64,'. base64_encode($content);
//                $result = ['image' => base64_encode($content)];
//                return json($result);
//                return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
        }
        $data = ['userinfo' => $userinfo];
        $this->success(__('ok'), $data);
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        if($this->auth->isLogin()) {
            $this->auth->logout();
        }
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $username = '';
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if(empty($nickname)){
            $this->error('请填写昵称');
        }
        if(empty($avatar)){
            $this->error('请上传头像');
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
//            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Nickname already exists'));
//            }
            $user->nickname = $nickname;
        }
//        $user->bio = $bio;
        if($avatar) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     * @ApiInternal
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        return;
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     * @ApiInternal
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        return;
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     * @ApiInternal
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        return;
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }



    /**
     * 申请找回密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="string", required=true, description="ID")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="password", type="string", required=true, description="新密码")
     * @ApiParams (name="newpassword", type="string", required=true, description="确认新密码")
     */
    public function apply_find_pwd(){
        $id = $this->request->post("id");
        $mobile = $this->request->post("mobile");
        $password = $this->request->post("password");
        $newpassword = $this->request->post("newpassword");
        if(empty($id)){
            $this->error('请输入ID');
        }
        if(empty($mobile)){
            $this->error('请输入手机号');
        }
        if(empty($password)){
            $this->error('请输入新密码');
        }
        if(empty($newpassword)){
            $this->error('请再次输入新密码');
        }
        if($password != $newpassword){
            $this->error('新密码不匹配');
        }
        $user = \app\common\model\User::where('username|id', $id)->find();
//        var_dump(\app\common\model\User::getLastSql(),$user);die;
        if(empty($user)){
            $this->error('ID错误');
        }
        if($user['status'] != 'normal'){
//            $this->error('ID状态异常,请联系管理员');
        }
        $data = [
            'user_id' => $user['id'],
            'apply_id' => $id,
            'apply_mobile' => $mobile,
            'apply_pwd' => $password,
        ];
        \app\common\model\ApplyFindPwd::create($data);
        $this->success('已申请，请联系管理员审核');
    }


    /**
     * 申请找回支付密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="string", required=true, description="ID")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="password", type="string", required=true, description="新密码")
     * @ApiParams (name="newpassword", type="string", required=true, description="确认新密码")
     */
    public function apply_find_pay_pwd(){
        $id = $this->request->post("id");
        $mobile = $this->request->post("mobile");
        $password = $this->request->post("password");
        $newpassword = $this->request->post("newpassword");
        if(empty($id)){
            $this->error('请输入ID');
        }
        if(empty($mobile)){
            $this->error('请输入手机号');
        }
        if(empty($password)){
            $this->error('请输入新密码');
        }
        if(empty($newpassword)){
            $this->error('请再次输入新密码');
        }
        if($password != $newpassword){
            $this->error('新密码不匹配');
        }
        $user = \app\common\model\User::where('username|id', $id)->find();
//        var_dump(\app\common\model\User::getLastSql(),$user);die;
        if(empty($user)){
            $this->error('ID错误');
        }
        if($user['status'] != 'normal'){
//            $this->error('ID状态异常,请联系管理员');
        }
        $data = [
            'user_id' => $user['id'],
            'apply_id' => $id,
            'apply_mobile' => $mobile,
            'apply_pwd' => $password,
        ];
        \app\common\model\ApplyFindPayPwd::create($data);
        $this->success('已申请，请联系管理员审核');
    }

    /**
     * 重置密码
     *
     * @ApiInternal
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        return;
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 转账积分到自己活动积分
     *
     * @ApiMethod (POST)
     * @ApiParams (name="points", type="float", required=true, description="积分", default="1")
     * @ApiParams (name="pay_pwd", type="string", required=false, description="支付密码", default="")
     * @ApiInternal
     */
    public function transferPointsToSelf(){
        $this->error();

        //手续费
//        $fee_rate = config('transfer_points_to_activity_points_rate') / 100;
        $fee_rate = config('site.points_to_activity_points_rate') / 100;
        $points = input('points/f');
        if($points <= 0){
            $this->error('积分参数错误');
        }
        //获取小数点位置
        $pos = strpos($points, '.');
        if($pos > 0){
            $other = substr($points, $pos + 1);
            if(strlen($other) > 2){
                $this->error('请保留小数点后最多两位数字');
            }
        }
        $pay_pwd = input('pay_pwd');
        if(empty($pay_pwd)){
            $this->error('请输入支付密码');
        }
        if($pay_pwd){
            if($this->auth->pay_password != $this->auth->getEncryptPassword($pay_pwd, $this->auth->salt)){
                $this->error('支付密码错误');
            }
        }
        $field = 'points';
        $user_val = $this->auth->points;
//        var_dump($user_val);die;
        $total_points = $points * (1 + $fee_rate);
        $fee = $points * $fee_rate;
        if($user_val < $total_points){
            $this->error('积分不足');
        }
        $user_id = $this->auth->id;
        $sn = Tools::getOrderSn();
        Db::startTrans();
        try{
            //减少自己的积分
            \app\common\model\User::points(2, $sn,$fee, -$total_points, $user_id, '转出');
            //增加自己的活动积分
            \app\common\model\User::activity_points(1, $sn, $points, $user_id, '收入');
            //增加系统的活动积分(手续费)
            \app\common\model\SystemData::activity_points(1, $sn, $total_points, $fee, '转出手续费');
            Db::commit();
        }catch (\think\Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 转账绿色积分到他人绿色积分
     *
     * @ApiMethod (POST)
     * @ApiParams (name="points", type="float", required=true, description="积分", default="1")
     * @ApiParams (name="receive_id", type="int", required=true, description="收款方账号(id或昵称)", default="1")
     * @ApidParams (name="receive_nickname", type="string", required=true, description="扣减人昵称", default="")
     * @ApiParams (name="receive_tel", type="string", required=false, description="扣减人电话", default="")
     * @ApiParams (name="pay_pwd", type="string", required=false, description="扣减人支付密码", default="")
     */
    public function transferPointsToOther(){
//        $receive_id = input('receive_id/d');
//        $receive_nickname = xss_clean(input('receive_nickname'));
//        $receive_tel = input('receive_tel/d');
//        if($receive_id <= 0 && !$receive_nickname){
//            $this->error('请输入扣减人ID');
//        }
//        if($receive_id > 0) {
//            $receive = \app\common\model\User::get($receive_id);
//        }else{
//            $receive = \app\common\model\User::get(['nickname' => $receive_nickname]);
//        }
        $receive_id = xss_clean(input('receive_id'));
        $receive_tel = input('receive_tel/d');
        $receive = \app\common\model\User::get(['username|id' => $receive_id]);
        if(empty($receive)){
            $this->error('扣减人错误');
        }
        if($receive['status'] != 'normal'){
            $this->error('扣减人状态异常');
        }

        if($receive_tel && $receive['mobile']) {
            if ($receive['mobile'] != $receive_tel){
                $this->error('扣减人电话错误');
            }
        }
        $pay_pwd = input('pay_pwd');
        if(empty($pay_pwd)){
            $this->error('请输入支付密码');
        }
        if($pay_pwd){
            if($this->auth->pay_password != $this->auth->getEncryptPassword($pay_pwd, $this->auth->salt)){
                $this->error('支付密码错误');
            }
        }
        //手续费
        $fee_rate = config('transfer_points_to_activity_points_rate') / 100;
        $fee_rate = config('site.points_to_activity_points_rate') / 100;
        // $fee_rate = 1;
        $points = input('points/f');
        if($points <= 0){
            $this->error('积分参数错误');
        }
        //获取小数点位置
        $pos = strpos($points, '.');
        if($pos > 0){
            $other = substr($points, $pos + 1);
            if(strlen($other) > 2){
                $this->error('请保留小数点后最多两位数字');
            }
        }
        $field = 'points';
        $user_val = $this->auth->activity_points;
//        var_dump($user_val);die;
        if($user_val < $points){
            $this->error('积分不足');
        }
        $user_id = $this->auth->id;
        $fee = $points * $fee_rate;
        // $fee = 0;
        $sn = Tools::getOrderSn();
        Db::startTrans();
        try{
            //增加系统手续费
            \app\common\model\SystemData::fee($fee, $user_id, '转账手续费');
            //减少自己的绿色积分
            \app\common\model\User::activity_points(2, $sn, -$points - $fee, $user_id, '转出');
            //增加他人的绿色积分
            \app\common\model\User::activity_points(1, $sn,$points, $receive_id, '转入');
            Db::commit();
        }catch (\think\Exception $e){
            Db::rollback();
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 获取积分记录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="type", type="int", required=false, sample="0", description="类型:0:全部,1:收入,2:支出,3:自提", default="0")
     * @ApiParams (name="page", type="int", required=false, sample="1", description="页码,默认=1", default="1")
     * @ApiParams (name="limit", type="int", required=false, sample="10", description="每页条数,默认=10", default="10")
     */
    public function getPointsList(){
        $params = input();
        $page = empty($params['page']) ? 1 : intval($params['page']);
        $limit = empty($params['limit']) ? 10 : intval($params['limit']);
        $type = empty($params['type']) ? 0 : intval($params['type']);
        if($type < 0 || $type > 3){
            $type = 0;
        }
        $return_data = [
            'list' => []
        ];
        $table = \app\common\model\UserPointsLog::alias('t');
        if($type){
//            if($type == 1){
//                $type = '2';
//            }
//            elseif($type == 2){
//                $type = ['3', '4'];
//            }
//            elseif($type == 3){
//                $type = '5';
//            }
            $table->whereIn('t.type', $type);
        }
        \think\Lang::load(APP_PATH . 'admin/lang/zh-cn/user_points_log.php');
        $fields = 'id,type,sn,fee,num,createtime';
        $res = $table->field($fields)->order('id desc')
            ->where('t.user_id', $this->auth->id)
            ->paginate($limit, false, ['page' => $page])
            ->each(function($item){
                $item['fee'] = fixNum($item['fee']);
                $item['num'] = fixNum($item['num']);
                $item['createtime_str'] = date('Y-m-d H:i', $item['createtime']);
            });
        $sql = $table->getLastSql();
        $list = $res->items();
        $return_data['list'] = $list;
        $return_data['total'] = $res->total();
        $return_data['sql'] = $sql;
        $this->success('返回成功', $return_data);
    }

    /**
     * 获取绿色积分记录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="type", type="int", required=false, sample="0", description="类型:0:全部,1:收入,2:支出,3:自提", default="0")
     * @ApiParams (name="page", type="int", required=false, sample="1", description="页码,默认=1", default="1")
     * @ApiParams (name="limit", type="int", required=false, sample="10", description="每页条数,默认=10", default="10")
     */
    public function getActivityPointsList(){
        $params = input();
        $page = empty($params['page']) ? 1 : intval($params['page']);
        $limit = empty($params['limit']) ? 10 : intval($params['limit']);
        $type = empty($params['type']) ? 0 : intval($params['type']);
        if($type < 0 || $type > 3){
            $type = 0;
        }
        $return_data = [
            'list' => []
        ];
        $table = \app\common\model\UserActivityPointsLog::alias('t');
        if($type){
//            if($type == 1){
//                $type = '2';
//            }
//            elseif($type == 2){
//                $type = ['3', '4'];
//            }
//            elseif($type == 3){
//                $type = '5';
//            }
            $table->whereIn('t.type', $type);
        }
        \think\Lang::load(APP_PATH . 'admin/lang/zh-cn/user_activity_points_log.php');
        $fields = 'id,type,sn,num,createtime';
        $res = $table->field($fields)->order('id desc')
            ->where('t.user_id', $this->auth->id)
            ->paginate($limit, false, ['page' => $page])
            ->each(function($item){
                $item['num'] = fixNum($item['num']);
                $item['createtime_str'] = date('Y-m-d H:i', $item['createtime']);
            });
        $sql = $table->getLastSql();
        $list = $res->items();
        $return_data['list'] = $list;
        $return_data['total'] = $res->total();
        $return_data['sql'] = $sql;
        $return_data['activity_points'] = fixNum($this->auth->activity_points);
        //获取累计收入和累计支出
        $res = \app\common\model\UserActivityPointsLog::alias('t')
            ->where('user_id', $this->auth->id)
            ->field('sum(case when num > 0 then num else 0 end) as plus,sum(case when num < 0 then num else 0 end) as minus')->find();
//        var_dump($res);
        $return_data['total_plus'] = fixNum($res['plus'] ?? 0);
        $return_data['total_minus'] = fixNum($res['minus'] ?? 0);
        $this->success('返回成功', $return_data);
    }

    /**
     * 获取宝豆记录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="type", type="int", required=false, sample="0", description="类型:0:全部,1:充值,2:奖励,3:扣减,4=转换", default="0")
     * @ApiParams (name="page", type="int", required=false, sample="1", description="页码,默认=1", default="1")
     * @ApiParams (name="limit", type="int", required=false, sample="10", description="每页条数,默认=10", default="10")
     */
    public function getCargoValueList(){
        $params = input();
        $page = empty($params['page']) ? 1 : intval($params['page']);
        $limit = empty($params['limit']) ? 10 : intval($params['limit']);
        $type = empty($params['type']) ? 0 : intval($params['type']);
        if($type < 0 || $type > 4){
            $type = 0;
        }
        $return_data = [
            'list' => []
        ];
        $table = \app\common\model\UserCargoValueLog::alias('t');
        if($type){
//            if($type == 1){
//                $type = '2';
//            }
//            elseif($type == 2){
//                $type = ['4'];
//            }
//            elseif($type == 3){
//                $type = '3';
//            }
//            elseif($type == 4){
//                $type = '5';
//            }
            $table->whereIn('t.type', $type);
        }
        \think\Lang::load(APP_PATH . 'admin/lang/zh-cn/user_cargo_value_log.php');
        $fields = 'id,type,sn,fee,num,createtime';
        $res = $table->field($fields)->order('id desc')
            ->where('t.user_id', $this->auth->id)
            ->paginate($limit, false, ['page' => $page])
            ->each(function($item){
                $item['fee'] = fixNum($item['fee']);
                $item['num'] = fixNum($item['num']);
                $item['createtime_str'] = date('Y-m-d H:i', $item['createtime']);
            });
        $sql = $table->getLastSql();
        $list = $res->items();
        $return_data['list'] = $list;
        $return_data['total'] = $res->total();
        $return_data['sql'] = $sql;
        $this->success('返回成功', $return_data);
    }

    /**
     * 获取团队列表
     *
     * @ApiMethod (POST)
     */
    public function team_list(){
        $user_id = $this->auth->id;
        $res = \addons\jiezicommon\service\Tools::getInstance()->getUserChindPath($user_id, 2, '', 'asc');
        // var_dump($res);die;
        $vip_person_num = 0;
        //个人累计货值
        $total_person_cargo_value = 0;
        //团队累计货值
        $total_team_cargo_value = 0;
        foreach($res as $idx => &$val){
            $val['jointime_str'] = date('Y-m-d H:i', $val['jointime']);
            $_order = $val['parent_speed_order_id'] ?\app\common\model\Order::where('id', $val['parent_speed_order_id'])->field('order_amount,createtime')->find() : [];
            
            $val['total_money'] = $_order['order_amount'] ?? 0;
            // $val['total_cargo_value'] = $val['total_money'];
            
            $val['total_money'] = $val['total_cargo_value'];
            
            $val['ordertime_str'] = !empty($_order['createtime']) ? date('Y-m-d H:i', $_order['createtime']) : '';
            $total_team_cargo_value += $val['total_cargo_value'];
            if($val['id'] == $user_id){
                $total_person_cargo_value = $val['total_cargo_value'];
                unset($res[$idx]);
                continue;
            }
            if($val['group_id'] == 2 || $val['group_id'] == 3){
                $vip_person_num++;
            }
            // $customer_arr = \addons\jiezicommon\service\Tools::getInstance()->getUserChindPath($val['id'], 1, 'id');
            // unset($customer_arr[$val['id']]);
            // $val['customer_num'] = count($customer_arr);
            $val['customer_num'] = 0;
        }
//        $vip_person_arr = array_filter($res, function($value) {
////            var_dump($value);
//            return $value['group_id'] == 3 || $value['group_id'] == 2; // 示例条件：值大于3
//        });
//        var_dump($filteredArray);
        $return_data['total_person_num'] = count($res);
        $return_data['total_vip_person_num'] = $vip_person_num;
        $return_data['total_team_cargo_value'] = fixNum($total_team_cargo_value);//团队累计货值
        $return_data['total_person_cargo_value'] = fixNum($total_person_cargo_value);//个人累计货值
        $return_data['list'] = $res ? array_values($res) : [];
        $this->success('', $return_data);
    }


    /**
     * 公共数据,管理员电话
     *
     * @ApiMethod (POST)
     */
    public function common(){
        $return_data = [
            'admin_tel' => array_filter(explode("\r\n",config('site.admin_tel'))),
            'points_to_activity_points_rate' => config('site.points_to_activity_points_rate'),
        ];
        $this->success('', $return_data);
    }

    //切换运行类型calc_type,仓类型:1=新人仓,2=老人仓
    /**
     * @ApiInternal
     */
    public function auto_set_calc_type(){
        $this->error();

        $days = config("calc_type_to_2_days") ?? 100;
        $time = $days * 86400;
        $count = Db::name('user')->where('status', 'normal')->where('calc_manual_status', '1')->where('calc_type', '1')->where('createtime', '<', time() - $time)->where('cycle_endtime', '>', time())->update(['calc_type' => '2']);
        echo 'success:' . $count;
    }

    //设置自动计算状态calc_auto_status,同时生成下一期周期结束时间
    /**
     * @ApiInternal
     */

    public function clac_order_total($date = null, $days = 30){
        $this->error();

        //指定日期
        if($date){
            $date = is_numeric($date) ? $date : strtotime($date . ' 23:59:59');
            $time = $date;
        }else{
            $time = strtotime(date('Y-m-d 23:59:59'));
        }
        //指定周期天数
        if($days){

        }else{
            $days = 30;
        }
//        var_dump(date('Y-m-d H:i:s', $date));die;
        /*  after 25.03.12 start */
        //周日内满足金额
        $member_purchase_in_a_cycle = (float)config('site.member_purchase_in_a_cycle');
        $cycle_order_stat_model = new \app\common\model\CycleOrderStat();
        $order_status = ['4'];//已收货
        $order_status = ['2', '3', '4'];//已支付
        //获取周期结束时间cycle_endtime已过期的会员,并计算上一周期内订单总额是否满足要求并设置自动计算状态calc_auto_status,同时生成下一期周期结束时间
        //1.获取周期结束时间cycle_endtime已过期的会员
        $user_list = Db::name('user')->where('status', 'normal')->where('calc_manual_status', '1')
            ->where('cycle_endtime', '<', $time)
//            ->where('id', 10)
            ->select();
        echo 'sql:' . Db::name('user')->getLastSql();
        foreach($user_list as $u){
            list($last_start_time, $last_end_time, $next_end_time) = \addons\jiezicommon\service\Tools::calc_current_cycle_time($date ? $date : $u['cycle_endtime'], $days);
            //统计周期内订单
            $order_money = Db::name('order')->where('user_id', $u['id'])
                ->whereIn('status', $order_status)
                ->whereTime('paytime', 'between', [$last_start_time, $last_end_time])
                ->sum('goods_amount');
//            var_dump($order_money, Db::name('order')->getLastSql());die;
            //更新统计订单数据
            $stat_id = $cycle_order_stat_model->where('user_id', $u['id'])
                ->where('cycle_starttime', ($last_start_time))
                ->where('cycle_endtime', ($last_end_time))
                ->value('id');
            if($stat_id){
                $cycle_order_stat_model->where('id',$stat_id)->update(['cycle_order_money' => $order_money]);
            }else{
                $cycle_order_stat_model::create(['user_id' => $u['id'], 'cycle_starttime' => ($last_start_time), 'cycle_endtime' => ($last_end_time), 'cycle_order_money' => $order_money]);
            }
            //更新用户表周期内数据
            $update_user = [
                'cycle_endtime' => ($next_end_time),
                'cycle_order_money' => $order_money,
                'calc_auto_status' => $order_money > $member_purchase_in_a_cycle ? 1 : 0,
            ];
            Db::name('user')->where('id', $u['id'])->update($update_user);
        }

        echo '共:' . count($user_list) . PHP_EOL;
        echo 'success';die;
        var_dump(Db::name('user')->getLastSql(), $user_list);die;
        /*  after 25.03.12 end */
        /*  before 25.03.12 start */
        /**
         * SELECT
        DATE_ADD(DATE_SUB(CURRENT_DATE, INTERVAL MOD(DATEDIFF(CURRENT_DATE, '2000-01-01'), 20) DAY), INTERVAL 19 DAY) AS cycle_end_time;
         * 在这个语句里，DATEDIFF(CURRENT_DATE, '2000-01-01') 算出从 2000-01-01 到当前日期的天数，MOD 函数得出该天数对 20 取余的结果。
         * 接着，DATE_SUB 函数从当前日期减去这个余数，从而得到当前周期的起始日期。
         * 最后，DATE_ADD 函数在起始日期的基础上加上 19 天，得到当前周期的截止日期。
         */
        /**
         *
         * SELECT
        id,
        FROM_UNIXTIME(createtime, '%Y-%m-%d'),
        DATE_SUB(DATE_SUB(CURRENT_DATE, INTERVAL MOD(DATEDIFF(CURRENT_DATE, FROM_UNIXTIME(createtime, '%Y-%m-%d')), 5) DAY), INTERVAL 5 DAY) AS cycle_start_time,
        DATE_SUB(DATE_SUB(CURRENT_DATE, INTERVAL MOD(DATEDIFF(CURRENT_DATE, FROM_UNIXTIME(createtime, '%Y-%m-%d')), 5) DAY), INTERVAL 1 DAY) AS cycle_end_time
        from fa_user
         * 获取用户上一个周日的起止日期
         *
         * 豆包提问 写一个sql语句，表tb_user中有创建时间字段createtime，周期天数为20天,请查询出距离当前时间最近的上一个周期的开始时间和截止时间,和下一个周期截止时间
         * SELECT id, FROM_UNIXTIME(createtime, '%Y-%m-%d'), '2025-03-22', DATE_SUB(DATE_SUB('2025-03-22', INTERVAL MOD(DATEDIFF('2025-03-22', FROM_UNIXTIME(createtime, '%Y-%m-%d')), 5) DAY), INTERVAL 5 DAY) AS cycle_start_time, DATE_SUB(DATE_SUB('2025-03-22', INTERVAL MOD(DATEDIFF('2025-03-22', FROM_UNIXTIME(createtime, '%Y-%m-%d')), 5) DAY), INTERVAL 1 DAY) AS cycle_end_time, DATE_SUB(DATE_SUB('2025-03-22', INTERVAL MOD(DATEDIFF('2025-03-22', FROM_UNIXTIME(createtime, '%Y-%m-%d')), 5) DAY), INTERVAL -4 DAY) AS next_cycle_end_time from fa_user where status = 'normal' and calc_manual_status = '1'
         */
        $interval_days = 5;
        $interval_days_d = $interval_days - 1;
        //用户正常，且没有人工停止
        $query0 = "SELECT 
id,
FROM_UNIXTIME(createtime, '%Y-%m-%d'),
    DATE_SUB(DATE_SUB(CURRENT_DATE, INTERVAL MOD(DATEDIFF(CURRENT_DATE, FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY), INTERVAL $interval_days DAY) AS cycle_start_time,
    DATE_SUB(DATE_SUB(CURRENT_DATE, INTERVAL MOD(DATEDIFF(CURRENT_DATE, FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY), INTERVAL 1 DAY) AS cycle_end_time
from fa_user where status = 'normal' and calc_manual_status = '1'";
        $query = "SELECT 
id,
FROM_UNIXTIME(createtime, '%Y-%m-%d'),
'$date',
    DATE_SUB(DATE_SUB('$date', INTERVAL MOD(DATEDIFF('$date', FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY), INTERVAL $interval_days DAY) AS cycle_start_time,
    DATE_SUB(DATE_SUB('$date', INTERVAL MOD(DATEDIFF('$date', FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY), INTERVAL 1 DAY) AS cycle_end_time,
    DATE_SUB(DATE_SUB('$date', INTERVAL MOD(DATEDIFF('$date', FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY), INTERVAL -$interval_days_d DAY) AS next_cycle_end_time
from fa_user where status = 'normal' and calc_manual_status = '1'";
        var_dump($query);die;
        $list = Db::query($query);
        $order_status = ['4'];//已收货
        $order_status = ['2', '3', '4'];//已支付
        //周日内满足金额
        $member_purchase_in_a_cycle = (float)config('site.member_purchase_in_a_cycle');
        $cycle_order_stat_model = new \app\common\model\CycleOrderStat();
        foreach($list as $it){
            //统计周期内订单
            $order_money = Db::name('order')->where('user_id', $it['id'])
                ->whereIn('status', $order_status)
                ->whereTime('paytime', 'between', [$it['cycle_start_time'], $it['cycle_end_time']])
                ->sum('goods_amount');
//            var_dump($order_money, Db::name('order')->getLastSql());die;
            //更新统计订单数据
            $stat_id = $cycle_order_stat_model->where('user_id', $it['id'])
                ->where('cycle_starttime', strtotime($it['cycle_start_time']))
                ->where('cycle_endtime', strtotime($it['cycle_end_time']))
                ->value('id');
            if($stat_id){
                $cycle_order_stat_model->where('id',$stat_id)->update(['cycle_order_money' => $order_money]);
            }else{
                $cycle_order_stat_model::create(['user_id' => $it['id'], 'cycle_starttime' => strtotime($it['cycle_start_time']), 'cycle_endtime' => strtotime($it['cycle_end_time']), 'cycle_order_money' => $order_money]);
            }
            //更新用户表周期内数据
            $update_user = [
                'cycle_endtime' => strtotime($it['cycle_end_time']),
                'cycle_order_money' => $order_money,
            ];
            Db::name('user')->where('id', $it['id'])->update($update_user);
        }
        /*  before 25.03.12 end */
        echo 'success';
//        var_dump($list);
    }

    //自动转化货值到积分
    /**
     *
     * @ApiInternal
    积分转换机制
    新人仓：当日货值总数÷3÷12÷30÷当日积分价格=当日转换积分
    老人仓：当日货值总数÷5÷12÷30÷当日积分价格=当日转换积分

    剩余货值总数=当日货值总数—当日转换积分×当日价格
     */
    public function auto_transfer_point($user_id = null){
        $this->error();

        $is_on = config('site.calc_run');
//        var_dump($is_on);die;
        $auto_transfer_point_day = \think\Cache::get('auto_transfer_point_day');
        if($is_on && $auto_transfer_point_day != date('Ymd')) {
            //当日积分价格
            $points_price = config('site.points_price');
            //calc_auto_status=1必须为可转化态
            $table = Db::name('user')->alias('u');
            if($user_id){
                $table->where('id', $user_id);
            }
            $user_list = $table->where('status', 'normal')
            ->where('calc_manual_status', '1')
            ->where('calc_auto_status', '1')
            ->where('cargo_value', '>', 0)
            ->field('id,cargo_value,calc_type')
            ->select();
            foreach ($user_list as $u) {
                //当日转换积分
                $curr_transfer_point = bcdiv($u['cargo_value'], 12 * 30, 6);
                $curr_transfer_point = bcdiv($curr_transfer_point, $points_price, 6);
                $curr_transfer_point = bcdiv($curr_transfer_point, $u['calc_type'] == 1 ? 3 : 5, 6);
                $change_val = $curr_transfer_point * $points_price;
                $sn = Tools::getOrderSn();
                //减少货值
                \app\common\model\User::cargo_value(4, $sn, 0, -$change_val, $u['id'], '货值转积分');
                //增加积分
                \app\common\model\User::points(1, $sn, 0, $curr_transfer_point, $u['id'], '货值转积分');
            }
            \think\Cache::set('auto_transfer_point_day', date('Ymd'));
        }else{
            $user_list = [];
        }
        if(request()->isAjax()){
            $this->success();
        }
        echo 'success:total_num:' . count($user_list);
    }

    public function test($date = null){
        $this->error();

        $interval_days = 5;
        if($date){

        }else{
            $date = date('Y-m-d');
        }

        $query = "SELECT 
            id,
            FROM_UNIXTIME(createtime, '%Y-%m-%d') AS creation_date,
            CURDATE() AS curr_date,
            DATE_SUB(
                CURDATE(), 
                INTERVAL MOD(DATEDIFF(CURDATE(), FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY
            ) AS cycle_start_date,
            DATE_ADD(
                DATE_SUB(
                    CURDATE(), 
                    INTERVAL MOD(DATEDIFF(CURDATE(), FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY
                ),
                INTERVAL ($interval_days - 1) DAY
            ) AS cycle_end_date,
            DATE_ADD(
                DATE_SUB(
                    CURDATE(), 
                    INTERVAL MOD(DATEDIFF(CURDATE(), FROM_UNIXTIME(createtime, '%Y-%m-%d')), $interval_days) DAY
                ),
                INTERVAL (2 * $interval_days - 1) DAY
            ) AS next_cycle_end_date
        FROM 
            fa_user
        WHERE 
            status = 'normal' AND calc_manual_status = '1';";

         var_dump($query);die;

        $list = Db::query($query);
        $order_status = ['4'];//已收货
        $order_status = ['2', '3', '4'];//已支付
        //周日内满足金额
        $member_purchase_in_a_cycle = (float)config('site.member_purchase_in_a_cycle');
        $cycle_order_stat_model = new \app\common\model\CycleOrderStat();
        foreach($list as $it){
            //统计周期内订单
            $order_money = Db::name('order')->where('user_id', $it['id'])
                ->whereIn('status', $order_status)
                ->whereTime('createtime', 'between', [$it['cycle_start_date'], $it['cycle_end_date']])
                ->sum('order_amount');
        //    var_dump($order_money, Db::name('order')->getLastSql());die;
            //更新统计订单数据
            $stat_id = $cycle_order_stat_model->where('user_id', $it['id'])
                ->where('cycle_starttime', strtotime($it['cycle_start_date']))
                ->where('cycle_endtime', strtotime($it['cycle_end_date']))
                ->value('id');
            if($stat_id){
                $cycle_order_stat_model->where('id',$stat_id)->update(['cycle_order_money' => $order_money]);
            }else{
                $cycle_order_stat_model::create(['user_id' => $it['id'], 'cycle_starttime' => strtotime($it['cycle_start_date']), 'cycle_endtime' => strtotime($it['cycle_end_date']), 'cycle_order_money' => $order_money]);
            }
            //更新用户表周期内数据
            $update_user = [
                'cycle_endtime' => strtotime($it['cycle_end_date']),
                'cycle_order_money' => $order_money,
            ];
            Db::name('user')->where('id', $it['id'])->update($update_user);
        }
        echo 'success';

    }

}
